package com.itxiao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itxiao.config.RedisKeyConfig;
import com.itxiao.dao.SpuDao;
import com.itxiao.dao.UserCollectDao;
import com.itxiao.entity.*;
import com.itxiao.pojo.dto.AddCollectDto;
import com.itxiao.pojo.vo.R;
import com.itxiao.service.UserCollectService;
import com.itxiao.util.Price;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * (UserCollect)表服务实现类
 *
 * @author makejava
 * @since 2025-10-17 14:54:38
 */
@Service()
public class UserCollectServiceImpl extends ServiceImpl<UserCollectDao, UserCollect> implements UserCollectService {
    @Resource
    private UserCollectDao userCollectDao;
    @Resource
    private SpuDao spuDao;
    @Resource
    private StringRedisTemplate template;

    @Override
    public R queryList(String token, Integer curPage, Integer pageSize) {
        // 从Redis获取用户信息
        User sysUser = JSON.parseObject(
                template.opsForValue().get(RedisKeyConfig.AUTH_LOGIN_TOKEN + token),
                User.class
        );
        if (sysUser == null) {
            return R.fail("解析令牌失败");
        }

        // 创建分页对象
        IPage<UserCollect> page = new Page<>(curPage, pageSize);

        // 执行分页查询
        IPage<UserCollect> userCollectPage = userCollectDao.selectPage(page, new LambdaQueryWrapper<>(UserCollect.class)
                .eq(UserCollect::getUserId, sysUser.getId())
                .orderByDesc(UserCollect::getCreateTime));

        List<UserCollect> userCollectList = userCollectPage.getRecords();
        if (userCollectList.isEmpty()) {
            return R.ok();
        }

        List<Long> spuIds = userCollectList.stream().map(UserCollect::getGoodsId).collect(Collectors.toList());
        List<Spu> spuList = spuDao.selectList(new LambdaQueryWrapper<>(Spu.class).in(Spu::getId, spuIds));
        Map<Long, Spu> spuMap = spuList.stream()
                .collect(Collectors.toMap(Spu::getId, spu -> spu));

        Map<String, Object> data = new HashMap<>();
        // 处理并组装数据
        List<Map<String, Object>> list = userCollectList.stream()
                .map(item -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", item.getId());
                    map.put("userId", item.getUserId());
                    map.put("spuId", item.getGoodsId());

                    Spu spu = spuMap.get(item.getGoodsId());
                    if (spu == null) {
                        return null;
                    }

                    map.put("title", spu.getTitle());
                    map.put("expressFee", spu.getExpressFee());
                    map.put("stock", spu.getStock());
                    map.put("salePrice", Price.IntToDecimal(spu.getSalePrice()));
                    map.put("suggestPrice", Price.IntToDecimal(spu.getSuggestPrice()));
                    map.put("thumbnail", spu.getThumbnail());
                    return map;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 添加分页信息到返回结果中
        data.put("list", list);
        data.put("total", userCollectPage.getTotal()); // 总记录数
        return R.ok(data);
    }

    @Override
    public R queryCollect(AddCollectDto dto, String token) {
        User sysUser = JSON.parseObject(
                template.opsForValue().get(RedisKeyConfig.AUTH_LOGIN_TOKEN + token),
                User.class
        );
        if (sysUser == null) {
            return R.fail("解析令牌失败");
        }
        UserCollect userCollect = userCollectDao.selectOne(new LambdaQueryWrapper<>(UserCollect.class)
                .eq(UserCollect::getUserId, sysUser.getId()).eq(UserCollect::getGoodsId, dto.getSpuId()));
        if (userCollect == null) {
            return R.ok(false);
        }
        return R.ok(true);
    }

    @Override
    public R add(AddCollectDto dto, String token) {
        User sysUser = JSON.parseObject(
                template.opsForValue().get(RedisKeyConfig.AUTH_LOGIN_TOKEN + token),
                User.class
        );
        if (sysUser == null) {
            return R.fail("解析令牌失败");
        }
        UserCollect userCollect = userCollectDao.selectOne(new LambdaQueryWrapper<>(UserCollect.class)
                .eq(UserCollect::getUserId, sysUser.getId()).eq(UserCollect::getGoodsId, dto.getSpuId()));
        if (userCollect != null) {
            return R.fail("用户已收藏，无需重复收藏");
        }
        UserCollect userCollect1 = new UserCollect();
        userCollect1.setUserId(sysUser.getId());
        userCollect1.setGoodsId(dto.getSpuId());
        int insert = userCollectDao.insert(userCollect1);
        if (insert <= 0) {
            return R.ok("添加失败");
        }
        return R.ok();
    }

    @Override
    public R deleteById(Integer id, String token) {
        User sysUser = JSON.parseObject(
                template.opsForValue().get(RedisKeyConfig.AUTH_LOGIN_TOKEN + token),
                User.class
        );
        if (sysUser == null) {
            return R.fail("解析令牌失败");
        }
        int delete = userCollectDao.delete(new LambdaQueryWrapper<>(UserCollect.class).eq(UserCollect::getGoodsId, id).eq(UserCollect::getUserId, sysUser.getId()));
        if (delete <= 0) {
            return R.fail("删除失败");
        }
        return R.ok();
    }
}

